#include "Avalon/WebServices/HttpServerResponse.hpp"
#include <boost/lexical_cast.hpp>
#include "Avalon/WebServices/HttpServer.hpp"
#include "Avalon/WebServices/HttpServerRequest.hpp"

using namespace Avalon;
using namespace Avalon::IO;
using namespace Avalon::WebServices;
using namespace boost;
using namespace std;

HttpServerResponse::~HttpServerResponse() {}

void HttpServerResponse::SetStatus(HttpStatusCode statusCode) {
  m_statusCode = statusCode;
}

void HttpServerResponse::SetHeader(const string& name, const string& value) {
  m_headers[name] = value;
}

void HttpServerResponse::SetBody(const Buffer& body) {
  m_body = body;
}

void HttpServerResponse::AddCookie(const Cookie& cookie) {
  m_cookies.push_back(cookie);
}

Buffer HttpServerResponse::Serialize() {
  SetHeader("Content-Length", lexical_cast<string>(m_body.GetSize()));
  string base = "HTTP/1.1 " + lexical_cast<string>(m_statusCode.GetValue()) +
    " " + m_statusCode.GetReasonPhrase() + "\r\n";
  for(map<string, string>::const_iterator i = m_headers.begin();
      i != m_headers.end(); ++i) {
    base += i->first + ": " + i->second + "\r\n";
  }
  for(vector<Cookie>::const_iterator i = m_cookies.begin();
      i != m_cookies.end(); ++i) {
    base += "Set-Cookie: " + i->ToString() + "\r\n";
  }
  base += "\r\n";
  Buffer data;
  data.Append(base.c_str(), base.size());
  data.Append(m_body);
  return data;
}

void HttpServerResponse::SendResponse() {
  m_server->SendResponse(this, m_channel);
}

HttpServerResponse::HttpServerResponse(HttpServer* server,
    HttpClientChannel* channel, HttpServerRequest* request)
    : m_server(server),
      m_channel(channel),
      m_request(request) {}
